using System;
using System.Reflection;
using UnityEngine;
namespace pd2_server_sdk.server
{
    public static class AnnotationScanner
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        public static void Initialize()
        {
            RegisterControllers();
            RegisterRoutes();
        }

        private static void RegisterControllers()
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.GetCustomAttribute<GameHandlerAttribute>() != null)
                    {
                        var instance = Activator.CreateInstance(type);
                        ControllerManager.Register(instance);
                        Debug.Log($"Registered controller: {type.Name}");
                    }
                }
            }
        }

        private static void RegisterRoutes()
        {
            foreach (var controller in ControllerManager.Controllers)
            {
                var methods = controller.GetType().GetMethods(
                    BindingFlags.Instance |
                    BindingFlags.Public |
                    BindingFlags.DeclaredOnly
                );

                foreach (var method in methods)
                {
                    var routeAttr = method.GetCustomAttribute<RouteAttribute>();
                    if (routeAttr != null)
                    {
                        Router.RegisterRoute(routeAttr.Path, method, controller);
                        Debug.Log($"Registered route: {routeAttr.Path} -> {method.Name}");
                    }
                }
            }
        }
    }
}